<?php
namespace App\Controller;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use App\Job\FootballArticleJob;
use Hyperf\Logger\LoggerFactory;

/**
 * @Controller(prefix="api/football")
 */
class FootballController
{
    protected $response;
    protected $queue;
    protected $loggerFactory;

    public function __construct(
        HttpResponse $response,
        DriverFactory $driverFactory,
        LoggerFactory $loggerFactory
    ) {
        $this->response = $response;
        $this->queue = $driverFactory->get('default');
        $this->loggerFactory = $loggerFactory;
    }

    /**
     * @GetMapping(path="football-article")
     */
    public function ifootballkitArticle(RequestInterface $request): ResponseInterface
    {
        try {
            $getData = $request->all();
            $webname = trim($getData['webname'] ?? '');

            if (empty($webname) || !is_string($webname)) {
                return $this->response->json([
                    'code' => 400,
                    'msg' => '参数 webname 必填，且为字符串'
                ]);
            }

            $conn = Db::connection($webname);
            $total = 0;

            $cursor = $conn->cursor("SELECT product_id FROM oc_product WHERE status = 1");

            foreach ($cursor as $product) {
                $this->queue->push(new FootballArticleJob(
                    (int)$product->product_id,
                    $getData,
                    $this->loggerFactory
                ));
                $total++;
            }

            return $this->response->json([
                'code' => 200,
                'msg' => "已推送{$total}条任务到队列",
            ]);

        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
}
